package com.tl.khadmin.service.impl;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import com.tl.khadmin.bean.GoodCat;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.tl.khadmin.bean.ProductBrand;
import com.tl.khadmin.bean.ProductType;
import com.tl.khadmin.bean.dto.ProductTypeTreeDto;
import com.tl.khadmin.mapper.ProductTypeMapper;
import com.tl.khadmin.page.Page;
import com.tl.khadmin.service.ProductIService;
import com.tl.khadmin.service.ProductTypeIService;
import com.tl.khadmin.util.CommonUtil;

@Service
public class ProductTypeServiceImpl implements ProductTypeIService{
	
	@Resource
	private ProductTypeMapper productTypeMapper;
	
	public List<ProductType> listProductType(Map<String, Object> param){
		return productTypeMapper.listProductType(param); 
	}

	/**
	 * 获取商品类型树形数据
	 */
	@Override
	public List<ProductTypeTreeDto> queryProductTypeTree(Map<String, Object> param) {
		List<ProductTypeTreeDto> typeList = productTypeMapper.listProductTypeTreeDto(param); 
		List<ProductTypeTreeDto> treeData = this.buildTree(typeList, 0);
		return treeData;
	}
	
	private List<ProductTypeTreeDto> buildTree(List<ProductTypeTreeDto> list, Integer parentId) {
        List<ProductTypeTreeDto> resultList = new ArrayList<>();
        for (ProductTypeTreeDto type : list) {
            Integer id = type.getId();
            Integer nowId = type.getParentId();
            if (nowId.intValue() == parentId.intValue()) {
                List<ProductTypeTreeDto> menuLists = buildTree(list, id);
                type.setSubset(menuLists);
                resultList.add(type);
            }
        }
        return resultList;
    }

	@Override
	public String saveProductType(ProductType productType) {
		Integer id = productTypeMapper.queryIdByTypeName(productType.getTypeName());
		if (id != null) {
			return CommonUtil.returnMapResultToJson("fail","类型名称已经存在");
		} 
		productType.setCreateTime(new Date()); 
		if(productType.getParentId() == null) {
			productType.setLevel(1);
		}else{
			productType.setLevel(productType.getLevel() + 1);
		}
		int result = productTypeMapper.insertSelective(productType);
		return CommonUtil.returnMapResultByRows(result, "添加成功", "添加失败，请重试");
	} 
	
	@Override
	public String updateProductType(ProductType productType) {
		Integer id = productTypeMapper.queryIdByTypeNameAndId( productType.getTypeName(), productType.getId());
		if (id != null) {
			return CommonUtil.returnMapResultToJson("fail","类型名称已经存在");
		}  
		int result = productTypeMapper.updateByPrimaryKeySelective(productType);
		return CommonUtil.returnMapResultByRows(result, "添加成功", "添加失败，请重试");
	}
	
	@Override
	public String deleteProductTypeById(HttpSession session,Integer id) { 
		Map<String, Object> param = new HashMap<>();
		param.put("parentId", id);
		List<ProductType> list = productTypeMapper.listProductType(param);
		if(list != null && list.size() > 0) {
			return CommonUtil.returnMapResultToJson("fail","请先删除子级");
		}
		return CommonUtil.returnMapResultByRows(productTypeMapper.deleteByPrimaryKey(id), "删除成功", "删除失败，请重试"); 
	}

	@Override
	public String syncProductType(GoodCat catInfo) {
         int id = productTypeMapper.queryByHaoLiBeiParentId(catInfo.getCatId());
		 ProductType type  = new ProductType();
		 if(catInfo.getParentId()>0){
		 	int partId = productTypeMapper.queryByHaoLiBeiParentId(catInfo.getParentId());
		 	if(partId>0){
		 		int length = catInfo.getCatPath().length();
		 		 if(length==1){
		 		 	type.setLevel(1);
				 }
		 		 else {
					 int length2 = catInfo.getCatPath().replace(",","").length();
					 type.setLevel(length-length2+1);
				 }
		 		type.setCreateTime(new Date());
		 		type.setParentId(partId);
		 		type.setTypeId(catInfo.getCatId());
		 		type.setTypeName(catInfo.getCatName());
		 		if(id>0){
					productTypeMapper.updateByPrimaryKeySelective(type);
				}
		 		else {
					productTypeMapper.insertSelective(type);
				}
		 		return  "100";
			}
		 	else {
		 		return "父类不存在";
			}
		 }
		 else {
			 type.setLevel(1);
			 type.setCreateTime(new Date());
			 type.setParentId(0);
			 type.setTypeId(catInfo.getCatId());
			 type.setTypeName(catInfo.getCatName());
			 if(id>0){
				 productTypeMapper.updateByPrimaryKeySelective(type);
			 }
			 else {
				 productTypeMapper.insertSelective(type);
			 }
			 return  "100";
		 }
	}


//	@Resource
//	private ShopProductMapper shopProductMapper;
//	@Resource
//	private ShopProductImgMapper shopProductImgMapper;
//	
//	@Override
//	public Map<String, Object> saveProduct(ShopProduct shopProduct) {
//		
//		Map<String, Object> map = new HashMap<String, Object>();
//		shopProduct.setCreatetime(new Date());
//		Integer result = shopProductMapper.insert(shopProduct);
//		Integer id = shopProduct.getId();
//		if(1 == result) {
//			map.put("result", "success");
//			map.put("message", id);
//			return map;
//		}else {
//			map.put("result", "fail");
//			return map;
//		}
//	}
//	

//
//	
//
//	@Override
//	public String deleteProductByIds(HttpSession session,String _ids) {
//		String[] ids = _ids.substring(0,_ids.length()-1).split(",");
//		int result = shopProductMapper.deleteProductByids(ids);
//		if(result==ids.length){
//			List<ShopProductImg> list = shopProductImgMapper.selectByProductIds(ids);
//			Integer ret2 = shopProductImgMapper.deleteImgByProductIds(ids);
//			if(list != null && list.size() == ret2){
//				String path = session.getServletContext().getRealPath("/");
//				for(int i=0;i<list.size();i++){
//					String root = path + list.get(i).getImgpath();
//					File  file = new File(root);  
//			        // 路径为文件且不为空则进行删除  
//			        if (file.isFile() && file.exists()) {  
//			            file.delete();  
//			        }
//				}
//				return CommonUtil.returnMapResultByRows(1, "删除成功","删除失败，请重试");
//			}
//			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事物回滚
//		}
//		return CommonUtil.returnMapResultByRows(0, "删除成功","删除失败，请重试");
//	}
//
//	@Override
//	public Map<String, Object> queryProductById(Integer id) {
//		
//		Map<String, Object> result = new HashMap<>();
//		ShopProduct shopProduct = shopProductMapper.selectByPrimaryKey(id);
//		List<ShopProductImg> shopProductImgs = shopProductImgMapper.selectByproductId(id);
//		result.put("product", shopProduct);
//		result.put("imglist", shopProductImgs);
//		return result;
//	}
//
//	@Override
//	public Map<String, Object> updateProduct(HttpSession session,ShopProduct shopProduct,String productImgIds) {
//		
//		Integer result = shopProductMapper.updateByPrimaryKeySelective(shopProduct);
//		Map<String, Object> map = new HashMap<String, Object>();
//		if(1 != result) {
//			map.put("result", "fail");
//			return map;
//		}
//		if(productImgIds != null && productImgIds.length() > 0){
//			String[] ids = productImgIds.substring(0,productImgIds.length()-1).split(",");
//			List<ShopProductImg> list = shopProductImgMapper.selectByIds(ids);
//			int ret = shopProductImgMapper.deleteImgByIds(ids);
//			if(ids.length != ret){
//				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事物回滚
//				map.put("result", "fail");
//				return map;
//			}
//			String path = session.getServletContext().getRealPath("/");
//			for(int i=0;i<list.size();i++){
//				String root = path + list.get(i).getImgpath();
//				File  file = new File(root);  
//		        // 路径为文件且不为空则进行删除  
//		        if (file.isFile() && file.exists()) {  
//		            file.delete();  
//		        }
//			}
//		}
//		map.put("result", "success");
//		return map;
//	}
//
//	@Override
//	public Integer deleteProductImgByProductId(Integer productid) {
//		
//		return shopProductImgMapper.deleteImgByProductId(productid);
//	}
//
//	@Override
//	public int queryCountByProductId(Integer productid) {
//
//		return shopProductImgMapper.selectCountByproductId(productid);
//	}
//
//	@Override
//	public int updateState(Integer id, Integer state) {
//		ShopProduct shopProduct = new ShopProduct();
//		shopProduct.setId(id);
//		shopProduct.setState(state);
//		return shopProductMapper.updateByPrimaryKeySelective(shopProduct);
//	}
//
//	@Override
//	public int updateProductImg(HttpSession session,ShopProductImg productImg) {
//		Map<String,Object> map = new HashMap<>();
//		map.put("productid", productImg.getProductid());
//		map.put("type", productImg.getType());
//		ShopProductImg shopProductImg = shopProductImgMapper.selectByKey(map);
//		String path = session.getServletContext().getRealPath("/");
//		path = path + shopProductImg.getImgpath();
//		File  file = new File(path);  
//        // 路径为文件且不为空则进行删除  
//        if (file.isFile() && file.exists()) {  
//            file.delete();  
//        }
//        ShopProduct newProduct = new ShopProduct();
//		newProduct.setId(productImg.getProductid());
//		newProduct.setImgurl(productImg.getImgpath());
//		Integer result = shopProductMapper.updateByPrimaryKeySelective(newProduct);
//		if(result!=1){
//			return result;
//		}
//		return shopProductImgMapper.updateImgByProductId(productImg);
//	}

}
